
import sys
import os
import logging
from logging import Logger, getLogger, StreamHandler
from nose.plugins import Plugin
from nose.plugins.logcapture import MyMemoryHandler
log = logging.getLogger()

class NoReallyStopLogging(Plugin):
    """The "No Really, Stop Logging" plugin.
    """
    enabled = True
    score = 501
    
    def options(self, parser, env):
        """Register commandline options.
        """

    def configure(self, options, conf):
        """Configure plugin.
        """

    def beforeTest(self, test):
        """Clear buffers and handlers before test.
        """
        root_logger = logging.getLogger()
        for handler in root_logger.handlers[:]:
            if not isinstance(handler, MyMemoryHandler):
                root_logger.removeHandler(handler)

def main():
    
    from appengine_django import InstallAppengineHelperForDjango
    InstallAppengineHelperForDjango()
    
    # kumar: custom installation
    import local_app
    local_app.install()
    
    for mod in ('nose', 'fudge'):
        # e.g. testlib/nose.zip/nose
        lib = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testlib', '%s.zip' % mod, mod))
        sys.path.append(lib)
    
    testrunner = os.path.basename(__file__)
    sys_args = []
    real_args = []
    state = 'sys'
    for a in sys.argv:
        if state == 'sys':
            sys_args.append(a)
        elif state == 'real':
            real_args.append(a)
        if a.endswith(testrunner):
            state = 'real'
    
    if not len(real_args) or real_args[0].startswith('-'):
        # Then no direct *test paths* were sent on the 
        # command line.  So let's preconfigure that with our
        # apps.  This is because otherwise nose will run all 
        # kinds of tests that will likely fail.
        from django.conf import settings
        for app in settings.INSTALLED_APPS:
            if not app.startswith('django') and not app.startswith('appengine_django'):
                # it is an app but also a relative path
                # that we want to pass into nose
                real_args.insert(0, app)
    
    from nose import main
    argv = (sys_args + real_args + ['--logging-clear-handlers'])
    log.info("Adjusted args: %s", argv)
    main(argv=argv, addplugins=[NoReallyStopLogging()])

if __name__ == '__main__':
    main()